package com.spring.boot.springBoot.threadPool;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by pactera on 2018/1/8.
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig {


    //线程池维护线程的最少数量
    private final int corePoolSize = 10;
    //线程池维护线程的最大数量
    private  final int maxPoolSize = 20;
    //缓存队列
    private final int queueCapacity = 8;
    //线程执行完保留时间
    private final int keepAlive = 60;

    @Bean
    public Executor threadPoolExcetor(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
        threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
        threadPoolTaskExecutor.setKeepAliveSeconds(keepAlive);
        threadPoolTaskExecutor.setThreadNamePrefix("ThreadPoolExcetor_");
        //如果当前线程数大于了最大线程数，使用自身线程处理
        // CALLER_RUNS：不在新线程中执行任务，而是由调用者所在的线程来执行
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }




}
